﻿using Abp.Dependency;
using Abp.Events.Bus.Handlers;
using AVIS.OutBound.Orders;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.ThirdOrders
{
    /// <summary>
    /// 第三方订单的相关事件处理
    /// </summary>
    public class ThirdOrderEventHandler :
        IEventHandler<OrderSubmittedEventData>,
        IEventHandler<OrderCanceledEventData>,
        ITransientDependency
    {

        #region 构造函数
        private readonly IAAOrderManager _aaOrderManager;
        private readonly IYouYouOrderManager _youyouOrderManager;

        public ThirdOrderEventHandler(
            IAAOrderManager aaOrderManager,
            IYouYouOrderManager youyouOrderManager
            )
        {
            _aaOrderManager = aaOrderManager;
            _youyouOrderManager = youyouOrderManager;
        }
        #endregion

        /// <summary>
        /// 订单已取消的事件处理：异步请求取消相关第三方订单
        /// </summary>
        /// <param name="eventData"></param>
        public void HandleEvent(OrderCanceledEventData eventData)
        {
            // 后续可以考虑采用后台任务的方式 IBackgroundJobManager
            _aaOrderManager.CancelAAOrder(eventData.Order.OrderNo);
            _youyouOrderManager.CancelYouYouOrder(eventData.Order.OrderNo);
        }

        /// <summary>
        /// 订单已提交的事件处理：异步保存第三方订单的数据（本地数据库存储）
        /// </summary>
        /// <param name="eventData"></param>
        public void HandleEvent(OrderSubmittedEventData eventData)
        {
            if (!(eventData.IsNewOrder && !string.IsNullOrEmpty(eventData.Order.ThirdOrders)))
            {
                return;
            }

            var thirdOrders = JsonConvert.DeserializeObject<List<ThirdOrderModel>>(eventData.Order.ThirdOrders);
            foreach (var item in thirdOrders)
            {
                if (item.Type == OutBoundConsts.THIRD_PRODUCT_TYPE_WIFI)
                {
                    _youyouOrderManager.SaveOrder(eventData.Order, item);
                }
                else if (item.Type == OutBoundConsts.THIRD_PRODUCT_TYPE_AA)
                {
                    _aaOrderManager.SaveOrder(eventData.Order);
                }
            }
        }
    }
}
